package com.itfitness.opengl

import android.content.res.AssetManager
import android.graphics.SurfaceTexture
import android.opengl.GLSurfaceView
import androidx.camera.core.Preview
import androidx.lifecycle.LifecycleOwner
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

/**
 *
 * @ProjectName:    OpenGL
 * @Package:        com.itfitness.opengl
 * @ClassName:      MyRender
 * @Description:     java类作用描述
 * @Author:         itfitness
 * @CreateDate:     2023-03-11 12:49
 * @UpdateUser:     更新者：
 * @UpdateDate:     2023-03-11 12:49
 * @UpdateRemark:   更新说明：
 */
class MyRender:GLSurfaceView.Renderer, Preview.OnPreviewOutputUpdateListener{
    init {
        System.loadLibrary("OpenGLRender")
    }
    private external fun ndkSurfaceCreated(assetManager: AssetManager)
    private external fun ndkSurfaceChanged(width:Int,height:Int)
    private external fun ndkDrawFrame(textureId:Int)

    private val assetManager: AssetManager
    private var surfaceTexture:SurfaceTexture? = null
    private var textureId:Int = 0
    constructor(myGLSurfaceView: MyGLSurfaceView){
        this.assetManager = myGLSurfaceView.context.assets
        if(myGLSurfaceView.context is LifecycleOwner){
            CameraHelper(myGLSurfaceView.context as LifecycleOwner,this)
        }
    }

    override fun onSurfaceCreated(p0: GL10?, p1: EGLConfig?) {
        ndkSurfaceCreated(assetManager)
        surfaceTexture?.let {
            it.attachToGLContext(textureId)
        }
    }

    override fun onSurfaceChanged(p0: GL10?, p1: Int, p2: Int) {
        ndkSurfaceChanged(p1,p2)
    }

    override fun onDrawFrame(p0: GL10?) {
        surfaceTexture?.updateTexImage()
        ndkDrawFrame(textureId)
    }

    override fun onUpdated(output: Preview.PreviewOutput?) {
        output?.let {
            surfaceTexture = it.surfaceTexture
        }
    }
}